package main

import (
	"fmt"
	"reflect"
)

type user struct {
	name string
	age  int
}

type student struct {
	name    string
	age     int
	teacher string
	class   string
}

func createQuery(i interface{}) string {
	var sql string
	// 类型
	t := reflect.TypeOf(i)
	// 值
	v := reflect.ValueOf(i)
	// 该类型的特定类别
	k := t.Kind()

	// 判断类型的类别
	if k == reflect.Struct {
		// 打印字段数
		fmt.Println("Number of filelds ", v.NumField())
		// 判断类型
		sql = fmt.Sprintf("insert into %s values(", t.Name())
		// 遍历获取类型值
		for i := 0; i < v.NumField(); i++ {
			switch v.Field(i).Kind() {
			case reflect.Int:
				if i == 0 {
					sql = fmt.Sprintf("%s%d", sql, v.Field(i).Int())
				} else if i == v.NumField()-1 {
					sql = fmt.Sprintf("%s,%d)", sql, v.Field(i).Int())
				} else {
					sql = fmt.Sprintf("%s,%d", sql, v.Field(i).Int())
				}
			case reflect.String:
				if i == 0 {
					sql = fmt.Sprintf("%s\"%s\"", sql, v.Field(i).String())
				} else if i == v.NumField()-1 {
					sql = fmt.Sprintf("%s,\"%s\")", sql, v.Field(i).String())
				} else {
					sql = fmt.Sprintf("%s,\"%s\"", sql, v.Field(i).String())
				}
			default:
				fmt.Println("Unsupported type")
			}
		}
	}

	return sql
}

func main() {
	fmt.Println("反射实践应用")
	u := user{
		name: "dong",
		age:  10,
	}
	s := student{
		name:    "xixi",
		age:     10,
		teacher: "Mr.li",
		class:   "3class",
	}
	fmt.Println(createQuery(u))
	fmt.Println(createQuery(s))

}
